package com.efounder.chat.utils;

import android.media.AudioFormat;
import android.media.MediaCodec;
import android.media.MediaFormat;



import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;

/**
 * author : zzj
 * e-mail : zhangzhijun@pansoft.com
 * date   : 2018/9/11 10:09
 * desc   :音频编码
 * version: 1.0
 */
public class AudioCodecUtils {


    private MediaCodec mediaCodec;
    private BufferedOutputStream outputStream;
    private String mediaType = "OMX.google.aac.encoder";

    private String audioPath;

    ByteBuffer[] inputBuffers = null;
    ByteBuffer[] outputBuffers = null;

    //mime：用来表示媒体文件的格式 mp3为audio/mpeg；aac为audio/mp4a-latm；mp4为video/mp4v-es
    private String mine = "audio/mpeg";
// "OMX.qcom.audio.decoder.aac";
// "audio/mp4a-latm";


    public AudioCodecUtils() {
        File f = new File(ImageUtil.amrpath,
                System.currentTimeMillis()+".aac");
        createFile(f);
        audioPath = f.getAbsolutePath();
        try {
            outputStream = new BufferedOutputStream(new FileOutputStream(f));
//            Log.e("AudioEncoder", "outputStream initialized");
        } catch (Exception e) {
            e.printStackTrace();
        }


// mediaCodec = MediaCodec.createEncoderByType("audio/mp4a-latm");
        try {
            mediaCodec = MediaCodec.createEncoderByType("audio/mp4a-latm");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 设置音频采样率，44100是目前的标准，但是某些设备仍然支持22050，16000，11025
        final int kSampleRates[] = { 8000, 11025, 16000, 44100, 48000 };
        //比特率 声音中的比特率是指将模拟声音信号转换成数字声音信号后，单位时间内的二进制数据量，是间接衡量音频质量的一个指标
        final int kBitRates[] = {32000,64000,96000,128000};

        //初始化   此格式使用的音频编码技术、音频采样率、使用此格式的音频信道数（单声道为 1，立体声为 2）
//        MediaFormat mediaFormat = MediaFormat.createAudioFormat(
//                MediaFormat.MIMETYPE_AUDIO_AAC, kSampleRates[3], 1);
//        mediaFormat.setInteger(MediaFormat.KEY_AAC_PROFILE,  MediaCodecInfo.CodecProfileLevel.AACObjectLC);

        MediaFormat mediaFormat = new MediaFormat();
        mediaFormat.setString(MediaFormat.KEY_MIME, MediaFormat.MIMETYPE_AUDIO_AAC);



//        mediaFormat.setInteger(MediaFormat.KEY_AAC_PROFILE,
//                MediaCodecInfo.CodecProfileLevel.AACObjectLC);
//        mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, kBitRates[1]);
//        mediaFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 1024);// It will
        mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, 32000);
        //1表示单声道
        mediaFormat.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1);
        mediaFormat.setInteger(MediaFormat.KEY_CHANNEL_MASK, AudioFormat.ENCODING_PCM_16BIT);
        mediaFormat.setInteger(MediaFormat.KEY_SAMPLE_RATE, 16000);
        mediaFormat.setInteger(MediaFormat.KEY_AAC_PROFILE,2);
        mediaFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 8192*2);

        mediaCodec.configure(mediaFormat, null, null,
                MediaCodec.CONFIGURE_FLAG_ENCODE);
        mediaCodec.start();


        inputBuffers = mediaCodec.getInputBuffers();
        outputBuffers = mediaCodec.getOutputBuffers();
    }


    public void close() {
        try {
            mediaCodec.stop();
            mediaCodec.release();
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据讯飞返回的音频数据byte[] 编码成aac格式文件
     * @param input
     */
    public synchronized void offerEncoder(byte[] input) {
//        Log.e("AudioEncoder", input.length + " is coming");


        int inputBufferIndex = mediaCodec.dequeueInputBuffer(-1);
        if (inputBufferIndex >= 0) {
            ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
            inputBuffer.clear();


            inputBuffer.put(input);


            mediaCodec
                    .queueInputBuffer(inputBufferIndex, 0, input.length, 0, 0);
        }


        MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
        int outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 0);


// //trying to add a ADTS
        while (outputBufferIndex >= 0) {
            int outBitsSize = bufferInfo.size;
            int outPacketSize = outBitsSize + 7; // 7 is ADTS size
            ByteBuffer outputBuffer = outputBuffers[outputBufferIndex];


            outputBuffer.position(bufferInfo.offset);
            outputBuffer.limit(bufferInfo.offset + outBitsSize);


            byte[] outData = new byte[outPacketSize];
            addADTStoPacket(outData, outPacketSize);


            outputBuffer.get(outData, 7, outBitsSize);
            outputBuffer.position(bufferInfo.offset);

            // byte[] outData = new byte[bufferInfo.size];
            try {
                outputStream.write(outData, 0, outData.length);
            } catch (IOException e) {

                e.printStackTrace();
            }
//            Log.e("AudioEncoder", outData.length + " bytes written");


            mediaCodec.releaseOutputBuffer(outputBufferIndex, false);
            outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 0);


        }

    }


    /**
     * Add ADTS header at the beginning of each and every AAC packet. This is
     * needed as MediaCodec encoder generates a packet of raw AAC data.
     *
     * Note the packetLen must count in the ADTS header itself.
     **/
    public void addADTStoPacket(byte[] packet, int packetLen) {
        int profile = 2; // AAC LC
        // 39=MediaCodecInfo.CodecProfileLevel.AACObjectELD;
        int freqIdx = 8;  // 16000 采样率
        int chanCfg = 1; // 1 单声道


        // fill in ADTS data
        packet[0] = (byte) 0xFF;
        packet[1] = (byte) 0xF9;
        packet[2] = (byte) (((profile - 1) << 6) + (freqIdx << 2) + (chanCfg >> 2));
        packet[3] = (byte) (((chanCfg & 3) << 6) + (packetLen >> 11));
        packet[4] = (byte) ((packetLen & 0x7FF) >> 3);
        packet[5] = (byte) (((packetLen & 7) << 5) + 0x1F);
        packet[6] = (byte) 0xFC;
    }

    /**
     * 创建文件
     * @param f
     */
    public static void createFile(File f) {
        try {
            if (!f.exists())
                f.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回生成aac文件的路径
     * @return
     */
    public String getAudioPath() {
        return audioPath;
    }


//    public static void pcm2Amr(String pcmPath , String amrPath) {
//        FileInputStream fis;
//        try {
//            fis = new FileInputStream(pcmPath);
//            pcm2Amr(fis, amrPath);
//            fis.close();
//        } catch (FileNotFoundException e1) {
//            e1.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    public static void pcm2Amr(InputStream pcmStream, String amrPath) {
//        try {
//            AmrInputStream ais = new AmrInputStream(pcmStream);
//            OutputStream out = new FileOutputStream(amrPath);
//            byte[] buf = new byte[4096];
//            int len = -1;
//            /*
//             * 下面的AMR的文件头,缺少这几个字节是不行的
//             */
//            out.write(0x23);
//            out.write(0x21);
//            out.write(0x41);
//            out.write(0x4D);
//            out.write(0x52);
//            out.write(0x0A);
//            while((len = ais.read(buf)) >0){
//                out.write(buf,0,len);
//            }
//            out.close();
//            ais.close();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}
